package pers.chy.chyappointmentplatform.Controller;

import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.chy.chyappointmentplatform.Model.NoMapping.ReplyMsgDTO;
import pers.chy.chyappointmentplatform.Model.Yjyy_PdjhDTO;
import pers.chy.chyappointmentplatform.Model.Yjyy_ZsxxExtDTO;
import pers.chy.chyappointmentplatform.Service.CallNumberService;
import pers.chy.chyappointmentplatform.Service.ClinicBulletinBoardService;
import pers.chy.chyappointmentplatform.Socket.Server_PICC;
import pers.chy.chyappointmentplatform.Socket.Server_YM;
import pers.chy.chyappointmentplatform.Utils.ChyException;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 叫号控制器
 */
@RestController     // 使用此注解才可以返回html
@CrossOrigin        // 允许跨域请求
@RequestMapping("CallNumberController")
public class CallNumberController {


    @Autowired
    private CallNumberService callNumberService;

    @Autowired
    private ClinicBulletinBoardService clinicBulletinBoardService;

    @RequestMapping("callNext")
    public String callNext(@RequestBody Map params, HttpServletRequest request) {
        ReplyMsgDTO replyMsgDTO = new ReplyMsgDTO();

        // 日志
        Logger log = LoggerFactory.getLogger(CallNumberController.class); // 使用指定的类XXX初始化日志对象，方便在日志输出的时候，可以打印出日志信息所属的类。
        log.info("[Controller入参]：" + params);

        // 叫号
        try {
            Yjyy_PdjhDTO ret = callNumberService.doCallNext( /* 进入Service层处理业务，根据是否发生异常判断业务是否成功 */
                    params,
                    (String) request.getAttribute("ygdm"),
                    (String) request.getAttribute("ygxm"));
            // 业务成功
            replyMsgDTO.setStatus(true);
            replyMsgDTO.setDetail(new Gson().toJson(ret));
        } catch (Exception ex) {
            // 业务失败
            replyMsgDTO.setStatus(false);
            replyMsgDTO.setDetail(ex.getMessage());
            // 异常日志
            if (ex instanceof ChyException) log.error("[错误]" + ex.getMessage());
            else log.error("[不期望的异常]", ex);
        }

        //
        // 叫号成功后的操作（失败时不影响Controller的逻辑，仅记录日志）
        //
        if (replyMsgDTO.isStatus() == true) {

            try {


                // 参数解析
                long dlxh = Long.parseLong(params.get("dlxh").toString());
                String jhzs = params.get("jhzs").toString();
                String jhzsPcName = params.get("jhzsPcName").toString();
                String dlmc = params.get("dlmc").toString();
                String jhrygh = (String) request.getAttribute("ygdm"); // 从JWT获取当前操作人员
                String jhryxm = (String) request.getAttribute("ygxm");
                String ygksmc = (String) request.getAttribute("ksmc");
                String jhryzc = (String) request.getAttribute("ygzc");

                /*
                 *  1、通知客户端浏览器刷新列表（群发WebSocket）
                 * */
                ReplyMsgDTO socketMsgDTO = new ReplyMsgDTO();
                // 获取此队列的最新叫号数据（未叫号、已叫号）
                Map dataMap = callNumberService.getLatestData(dlxh);
                List<Yjyy_PdjhDTO> wjhList = (List) dataMap.get("wjh");
                List<Yjyy_PdjhDTO> yjhList = (List) dataMap.get("yjh");
                socketMsgDTO.setStatus(true);
                socketMsgDTO.setDetail(String.format("%s&%s",
                        new Gson().toJson(wjhList),
                        new Gson().toJson(yjhList)));
                String socketMsgDTOStr = new Gson().toJson(socketMsgDTO);
                // 向Socket客户端群发叫号数据
                if (dlxh == 1) { // 暂时写死
                    Server_PICC.BroadCastInfo(socketMsgDTOStr);
                } else {
                    Server_YM.BroadCastInfo(socketMsgDTOStr);
                }

                /*
                 *  2、诊显（异步调用集成平台）
                 * */
                clinicBulletinBoardService.doShow(
                        dlmc,
                        jhzs,
                        jhrygh,
                        jhryxm,
                        jhryzc,
                        "医生简介",
                        yjhList.size() != 0 ? yjhList.get(0).getBrxm() : "",
                        yjhList.size() != 0 ? String.valueOf(yjhList.get(0).getPdhm()) : "",
                        wjhList.size() != 0 ? wjhList.get(0).getBrxm() : "",
                        wjhList.size() != 0 ? String.valueOf(wjhList.get(0).getPdhm()) : "",
                        jhzsPcName
                );

            } catch (Exception ex) {
                // 异常日志
                if (ex instanceof ChyException) log.error("[错误]" + ex.getMessage());
                else log.error("[不期望的异常]", ex);
            }

        }


        String replyMsgStr = new Gson().toJson(replyMsgDTO);
        log.info("[Controller出参]：" + replyMsgStr);
        return replyMsgStr;
    }


    /**
     * 获取诊室信息（列表）
     *
     * @param params
     * @param request
     * @return
     */
    @RequestMapping("getZsxx")
    public String getZsxx(@RequestBody Map params, HttpServletRequest request) {
        ReplyMsgDTO replyMsgDTO = new ReplyMsgDTO();

        // 日志
        Logger log = LoggerFactory.getLogger(CallNumberController.class); // 使用指定的类XXX初始化日志对象，方便在日志输出的时候，可以打印出日志信息所属的类。
        log.info("[Controller入参]：" + params);

        /* 进入Service层处理业务，根据是否发生异常判断业务是否成功 */
        try {
            Long dlxh = Long.valueOf((Integer) params.get("dlxh"));
            List<Yjyy_ZsxxExtDTO> Yjyy_ZsxxList = callNumberService.getZsxx(dlxh);

            // 业务成功
            replyMsgDTO.setStatus(true);
            replyMsgDTO.setDetail(new Gson().toJson(Yjyy_ZsxxList));

        } catch (Exception ex) {
            // 业务失败
            replyMsgDTO.setStatus(false);
            replyMsgDTO.setDetail(ex.getMessage());
            // 异常日志
            if (ex instanceof ChyException) log.error("[错误]" + ex.getMessage());
            else log.error("[不期望的异常]", ex);
        }
        String replyMsgStr = new Gson().toJson(replyMsgDTO);
        log.info("[Controller出参]：" + replyMsgStr);
        return replyMsgStr;
    }


    /**
     * 重叫
     *
     * @param params
     * @param request
     * @return
     */
    @RequestMapping("reCall")
    public String reCall(@RequestBody Map params, HttpServletRequest request) {
        ReplyMsgDTO replyMsgDTO = new ReplyMsgDTO();

        // 日志
        Logger log = LoggerFactory.getLogger(CallNumberController.class); // 使用指定的类XXX初始化日志对象，方便在日志输出的时候，可以打印出日志信息所属的类。
        log.info("[Controller入参]：" + params);

        /* 进入Service层处理业务，根据是否发生异常判断业务是否成功 */
        try {
            callNumberService.reCall(params);

            // 业务成功
            replyMsgDTO.setStatus(true);

        } catch (Exception ex) {
            // 业务失败
            replyMsgDTO.setStatus(false);
            replyMsgDTO.setDetail(ex.getMessage());
            // 异常日志
            if (ex instanceof ChyException) log.error("[错误]" + ex.getMessage());
            else log.error("[不期望的异常]", ex);
        }
        String replyMsgStr = new Gson().toJson(replyMsgDTO);
        log.info("[Controller出参]：" + replyMsgStr);
        return replyMsgStr;
    }
}
